from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import List
import yaml
from prance import ResolvingParser
from jsonpath_ng import parse
from fastapi_offline import FastAPIOffline

app = FastAPIOffline()

#app = FastAPI()

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

class Endpoint(BaseModel):
    endpointName: str
    endpointId: str
    ip: str
    port: int
    type: int

class Link(BaseModel):
    linkId: str
    linkName: str
    level: str
    protected: int
    endpoints: List[Endpoint]

links_db = []

@app.post("/links", response_model=Link, status_code=201)
async def create_link(link: Link):
    links_db.append(link)
    return link

@app.get("/links", response_model=List[Link])
async def get_links():
    return links_db

@app.get("/links", response_model=Link)
async def get_link(linkId: str):
    link = next((link for link in links_db if link.linkId == linkId), None)
    if link is None:
        raise HTTPException(status_code=404, detail="Link not found")
    return link

@app.delete("/links", status_code=204)
async def delete_link(linkId: str):
    global links_db
    links_db = [link for link in links_db if link.linkId != linkId]
    if not any(link.linkId == linkId for link in links_db):
        raise HTTPException(status_code=404, detail="Link not found")
    return None



def generate_routes(app, spec):
    for path, path_item in spec['paths'].items():
        for method, operation in path_item.items():
            if method in ['get', 'post', 'put', 'delete']:
                operation_id = operation['operationId']
                app.add_api_route(path, lambda: {}, methods=[method.upper()], name=operation_id)

# 不需要动态加载路径
#spec = load_openapi_spec('openapi.yaml')
#generate_routes(app, spec)


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=12345)


